//
//  MixCellsViewController.m
//  Animations
//
//  Created by YouXianMing on 2016/11/24.
//  Copyright © 2016年 YouXianMing. All rights reserved.
//

#import "MixCellsViewController.h"
#import "UIColor+ForPublicUse.h"
#import "HeaderIconCell.h"
#import "ContentIconCell.h"
#import "ColorSpaceCell.h"
#import "ARLoginViewController.h"
#import "FeedbackViewController.h"
#import "WaterFulViewController.h"

#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

typedef enum : NSUInteger {
    
    kSpace = 1000,
    kLongType,
    kShortType,
    
} ELineTypeValue;

@interface MixCellsViewController ()    <
    UITableViewDelegate,
    UITableViewDataSource,
    CustomCellDelegate,
    iconGesturedelegate,
    UIImagePickerControllerDelegate,
    UINavigationControllerDelegate      >
{
    UIImagePickerController *_imagePickerController;
    HeaderIconCell *_headerCell;
    AVUser *_user;
}

@property (nonatomic, strong) NSMutableArray <CellDataAdapter *> *adapters;
@property (nonatomic, strong) UITableView                        *tableView;

@end

@implementation MixCellsViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
    [UIApplication sharedApplication].statusBarHidden = YES;

    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;

    if ([UIApplication sharedApplication].statusBarHidden == YES)
        [UIApplication sharedApplication].statusBarHidden = NO;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"iconImage"];
}

- (void)setup {
    
    _user = [AVUser currentUser];
    
    [super setup];
    
    [self createTableViewAndRegisterCells];
    
    [self createDataSource];
    
    [self baseConfig];
    
    //[self addExitBtn];
}

#pragma mark - Data source.


- (void)createDataSource {

    self.adapters = [NSMutableArray array];
    
    [self.adapters addObject:[HeaderIconCell dataAdapterWithData:nil cellHeight:HeaderIconCell.cellHeight]];
    [self.adapters addObject:[self lineType:kSpace height:AAdaption((20.f)/AAdaptionWidth())]];
    [self.tableView reloadData];
    
    [UIView animateWithDuration:0.75f animations:^{
        
        self.tableView.alpha = 1.f;
        
    } completion:^(BOOL finished) {
        
        [self.adapters addObject:[self lineType:kLongType height:AAdaption((0.5f)/AAdaptionWidth())]];
        [self.adapters addObject:[ContentIconCell dataAdapterWithData:@{@"icon" : @"signlist_new",   @"title" : @"个人中心"}  cellHeight:AAdaption((50.f)/AAdaptionWidth())]];
        
        [self.adapters addObject:[self lineType:kShortType height:AAdaption((0.5f)/AAdaptionWidth())]];
        [self.adapters addObject:[ContentIconCell dataAdapterWithData:@{@"icon" : @"collection_new", @"title" : @"福利收藏"} cellHeight:AAdaption((50.f)/AAdaptionWidth())]];
        
        [self.adapters addObject:[self lineType:kShortType height:AAdaption((0.5f)/AAdaptionWidth())]];
        [self.adapters addObject:[ContentIconCell dataAdapterWithData:@{@"icon" : @"drawer_setting", @"title" : @"设置"}        cellHeight:AAdaption((50.f)/AAdaptionWidth())]];
        
        [self.adapters addObject:[self lineType:kShortType height:AAdaption(0.5f/AAdaptionWidth())]];
        [self.adapters addObject:[ContentIconCell dataAdapterWithData:@{@"icon": @"ChaCha",@"title":@"登出"} cellHeight:AAdaption((50.f)/AAdaptionWidth())]];
        
        NSMutableArray *indexPaths = [NSMutableArray array];
        [self.adapters enumerateObjectsUsingBlock:^(CellDataAdapter *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [indexPaths addObject:[NSIndexPath indexPathForRow:idx inSection:0]];
        }];
        [indexPaths removeObjectsInRange:NSMakeRange(0, 2)];
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    }];
    
    
}

- (CellDataAdapter *)lineType:(ELineTypeValue)type height:(CGFloat)height {

    if (type == kSpace) {
    
        return [ColorSpaceCell dataAdapterWithData:nil cellHeight:50.f];
        
    } else if (type == kLongType) {
    
        return [ColorSpaceCell dataAdapterWithData:@{@"backgroundColor" : [UIColor whiteColor], @"lineColor" : [UIColor lineColor]} cellHeight:0.5f];
        
    } else if (type == kShortType) {
    
        return [ColorSpaceCell dataAdapterWithData:@{@"backgroundColor" : [UIColor whiteColor], @"lineColor" : [UIColor lineColor], @"leftGap" : @(50.f)} cellHeight:0.5f];
        
    } else {
    
        return nil;
    }
}

#pragma mark - UITableView related.

- (void)createTableViewAndRegisterCells {

    self.tableView                 = [[UITableView alloc] initWithFrame:self.contentView.bounds ];
    self.tableView.delegate        = self;
    self.tableView.dataSource      = self;
    self.tableView.alpha           = 0.f;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.tableView];
    
    [HeaderIconCell  registerToTableView:self.tableView];
    [ContentIconCell registerToTableView:self.tableView];
    [ColorSpaceCell  registerToTableView:self.tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _adapters.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CellDataAdapter *adapter = _adapters[indexPath.row];
    CustomCell      *cell    = [tableView dequeueReusableCellWithIdentifier:adapter.cellReuseIdentifier];
    cell.dataAdapter         = adapter;
    cell.data                = adapter.data;
    cell.indexPath           = indexPath;
    cell.tableView           = tableView;
    cell.delegate            = self;
    [cell loadContent];
    
    if (_headerCell == nil && [cell isKindOfClass:[HeaderIconCell class]]) {
        
        _headerCell = (HeaderIconCell *)cell;
        _headerCell.iconDelegate = self;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return _adapters[indexPath.row].cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [(CustomCell *)[tableView cellForRowAtIndexPath:indexPath] selectedEvent];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    [_headerCell offsetY:scrollView.contentOffset.y];
}

#pragma mark - CustomCellDelegate

- (void)customCell:(CustomCell *)cell event:(id)event {

    NSLog(@"%@", event);

    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSLog(@"%ld",indexPath.row);
    switch (indexPath.row) {
        case 3:
        {
            //个人中心
            [self reviseNikeName];
           
        }
            break;
        case 5:
        {
            //个人收藏
            __weak typeof(self) weakSelf = self;
            if ([[NSUserDefaults standardUserDefaults] boolForKey:isLoginKey]) {
                [self.navigationController pushViewController:[[WaterFulViewController alloc] init] animated:YES];
            }
            else {
            [[CLLScottAlertView alloc] showEffAlertViewWithTitle:@"提示" message:@"该部分内容要登录后才能看哦" WithSureBlock:^(ScottAlertAction *action) {
                [weakSelf presentViewController:[[ARLoginViewController alloc] init] animated:YES completion:nil];
            } WithCancelBlock:^(ScottAlertAction *action) {
                
            } WithVc:self];
            }
        }
            break;
        case 7:
        {
            //设置
            [self showDefaultActionSheetWithTitle:nil WithMessage:nil];
            
        }
            break;
        case 9:
        {
            if ([[NSUserDefaults standardUserDefaults]boolForKey:isLoginKey])
                [self beginExitLogin];
            else
                [self beginLogin];
            
        }
        break;
        default:
            break;
    }
}


//修改昵称
- (void)reviseNikeName {
 
    if ( [[NSUserDefaults standardUserDefaults] boolForKey:isLoginKey] )
    {
        [[CLLScottAlertView alloc] showTextfieldAlertViewWithTitle:@"修改昵称" WithMessage:nil WithVc:self WithSureBlock:^(ScottAlertAction *action) {
            
            [_user saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                
                if (!error) {
                    [CLLMessageBarTool showMessageWithType:TWMessageBarMessageTypeSuccess WithTitle:@"提示" WithDescription:@"修改成功"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"iconImage" object:nil];
                }
            }];

            
        } WithCancelBlock:^(ScottAlertAction *action) {
            
        } WithTextFiledText:^(NSString *text) {
            [_user setObject:text forKey:@"nikeName"];
        }];
    }
    else
    {
        [self beginLogin];
    }
    
}

///退出登录
- (void)beginExitLogin {
    [[CLLScottAlertView alloc] showEffAlertViewWithTitle:@"退出登录?" message:nil  WithSureBlock:^(ScottAlertAction *actionClicked) {
            NSLog(@"sure");
            [AVUser logOut];
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:isLoginKey];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"exitLogin" object:nil];
        
        } WithCancelBlock:^(ScottAlertAction *actionClicked) {
            NSLog(@"cancel");
        }WithVc:self];
    
}

//开始登录
- (void)beginLogin {
    
    __weak typeof(self) weakSelf = self;
    [[CLLScottAlertView alloc] showEffAlertViewWithTitle:@"提示" message:@"您还未登录,是否登录?" WithSureBlock:^(ScottAlertAction *action) {
        
        [weakSelf presentViewController:[[ARLoginViewController alloc] init] animated:YES completion:nil];
        
    } WithCancelBlock:^(ScottAlertAction *action){
        
    }WithVc:self];
}


#pragma mark - 弹窗

/// 默认形式的actionSheet
- (void)showDefaultActionSheetWithTitle:(NSString *)title WithMessage:(NSString *)message {
    
    __weak typeof(self) weakSelf = self;
    
    ScottAlertView *alertView = [ScottAlertView alertViewWithTitle:title message:message];
    
    [alertView addAction:[ScottAlertAction actionWithTitle:[NSString stringWithFormat:@"清除缓存(%.f M)",[self filePath]] style:ScottAlertActionStyleCancel handler:^(ScottAlertAction *action) {
        NSLog(@"%@",action.title);
        if ([weakSelf filePath] != 0.0)     [weakSelf clearFile];
    }]];
    
    [alertView addAction:[ScottAlertAction actionWithTitle:@"意见反馈" style:ScottAlertActionStyleCancel handler:^(ScottAlertAction *action) {
        NSLog(@"%@",action.title);
        [weakSelf.navigationController pushViewController:[[FeedbackViewController alloc] init] animated:YES];
    }]];
    [alertView addAction:[ScottAlertAction actionWithTitle:@"评价我们" style:ScottAlertActionStyleCancel handler:^(ScottAlertAction *action) {
        NSLog(@"%@",action.title);
    }]];
    
    ScottAlertViewController *alertController = [ScottAlertViewController alertControllerWithAlertView:alertView preferredStyle:ScottAlertControllerStyleActionSheet];
    alertController.tapBackgroundDismissEnable = YES;
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 头像点击手势

- (void)iconGestureResponderWithIcon:(UIImageView *)icon {
    NSLog(@"点击了头像");
    
    [self initImagePickerController];
    __weak typeof(self) weakSelf = self;
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:isLoginKey]) {
        
       SRActionSheet *sheet = [SRActionSheet sr_actionSheetViewWithTitle:@"修改头像" cancelTitle:@"取消" destructiveTitle:nil otherTitles:@[@"拍照",@"从相册选取"] otherImages:nil selectSheetBlock:^(SRActionSheet *actionSheet, NSInteger index) {
           
           if (index == 0)  [weakSelf openCamera];
           if (index == 1)  [weakSelf openPhotoAlbum];
           
        }];
        [sheet show];
        
    }
    else {
        ARLoginViewController *loginVC = [[ARLoginViewController alloc] init];
        [self presentViewController:loginVC animated:YES completion:nil];

    }

}

#pragma mark - 相机相册的调用

- (void)initImagePickerController {
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
}

//打开相机
- (void)openCamera {
    //判断是否可以打开照相机
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        //摄像头
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }
    else
    {
        [[CLLScottAlertView alloc] showOnWindowWithTitle:@"打开失败" WithMessage:@"照相机可能已损坏"];
    }
    
}

//打开相册
- (void)openPhotoAlbum {
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }
    else
    {
        [[CLLScottAlertView alloc] showOnWindowWithTitle:@"打开失败" WithMessage:@"照相机可能已损坏"];
    }
}

///拍照完成的回调
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    
        //图片存入相册
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        //压缩图片
        image = [self OriginImage:image];
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
   
        [self upLoadIconFileWithData:data];
    
    }
    [self dismissViewControllerAnimated:YES completion:nil];

}

//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


/// 图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{
    
}

#pragma mark - 缩放图片
- (UIImage*)OriginImage:(UIImage *)image
{
    CGSize size = CGSizeMake(110,110);
    UIGraphicsBeginImageContext(size);  //size 为CGSize类型，即你所需要的图片尺寸
    
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;   //返回的就是已经改变的图片
}


#pragma mark - 上传头像
- (void)upLoadIconFileWithData:(NSData *)data {
    
    if (_user == nil) {
        _user = [AVUser currentUser];
    }
    AVFile *iconFile = [AVFile fileWithData:data];
    
    NSString *iconFileId = [[NSUserDefaults standardUserDefaults] objectForKey:iconImageObjectID];
    
    if (iconFileId.length > 1) {
        [AVFile getFileWithObjectId:iconFileId withBlock:^(AVFile * _Nullable file, NSError * _Nullable error) {
            
            if (!error) {
                [file deleteInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                    NSLog(@"-----上传新头像前先删除旧的头像--------\n-------删除成功--------");
                }];
            }
            
        }];
         }
    
    [_user setObject:iconFile forKey:@"iconImage"];
    [_user saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        
        if (succeeded)  {
            [CLLMessageBarTool showMessageWithType:TWMessageBarMessageTypeSuccess WithTitle:@"提示" WithDescription:@"头像上传成功"];
            NSLog(@"----------------------头像上传成功后得到的头像的id\n--- - - -- - - - - -  - -%@",iconFile.objectId);
            
            [[NSUserDefaults standardUserDefaults] setObject:iconFile.objectId forKey:iconImageObjectID];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"iconImage" object:nil userInfo:nil];
        }
        else
             [CLLMessageBarTool showMessageWithType:TWMessageBarMessageTypeError WithTitle:@"提示" WithDescription:@"头像上传失败"];
        
    }];

}

//- (void)downLoadDataWithObjectId:(NSString *)Id {
//    
//    [AVFile getFileWithObjectId:Id withBlock:^(AVFile * _Nullable file, NSError * _Nullable error) {
//        if (!error) {
//            
//        [file getDataInBackgroundWithBlock:^(NSData * _Nullable data, NSError * _Nullable error) {
//            
//            UIImage *image = [UIImage imageWithData:data];
//            [[NSNotificationCenter defaultCenter]postNotificationName:@"iconImage" object:nil userInfo:@{@"iconImage":image}];
//            
//                }];
//        }else {
//            [[CLLMessageBarTool shareTool] showMessageWithType:TWMessageBarMessageTypeError WithTitle:@"提示" WithDescription:@"头像加载失败"];
//        }
//    }];
//}

#pragma mark - Base config.

- (void)baseConfig {
    
    self.backgroundView.backgroundColor = [UIColor backgroundColor];

    __block UIButton *backButton = nil;
    [self.titleView.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([obj isKindOfClass:[UIButton class]]) {
            
            UIButton *button = obj;
            if ([[button imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"backIcon"]]) {
                
                backButton = button;
            }
        }
    }];
    
    [self.contentView addSubview:backButton];
    [self.titleView removeFromSuperview];
}

#pragma mark - 清理缓存
/*
 * 1.显示缓存大小
 */
- (CGFloat)filePath {
    
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    return [self folderSizeAtPath:cachPath];
}
//遍历文件获得文件大小，单位M
- (CGFloat)folderSizeAtPath:(NSString *)folderPath {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) {
        return 0;
    }
    
    NSEnumerator *enumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString *fileName;
    NSInteger folderSize = 0;
    
    while ((fileName = [enumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1024.0 * 1024);
}
//计算单个文件大小
- (NSInteger)fileSizeAtPath:(NSString *)filePath {
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]) {
        return  [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

- (void)clearFile {
    //找到沙盒中存放缓存数据的文件夹路径
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    
    [files enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //
        NSError *error = nil;
        
        NSString *path = [cachPath stringByAppendingPathComponent:obj];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }];
    
    [self performSelectorOnMainThread:@selector(clearCachSuccess) withObject:nil waitUntilDone:YES];
}

//清理成功
- (void)clearCachSuccess {
    
    [[CLLScottAlertView alloc] showOnWindowWithTitle:@"提示" WithMessage:@"清理成功"];
    //[self showOnWindowWithTitle:@"提示" WithMessage:@"清理成功"];
}


@end
